package com.wlf.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.wlf.constant.Constants;
import com.wlf.dao.AccountMapper;
import com.wlf.entity.Account;
import com.wlf.entity.AccountExample;
import com.wlf.service.IAccountService;
import com.wlf.service.ITransferService;
import io.seata.spring.annotation.GlobalTransactional;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
* @author 作者 危凌峰:
* @version 创建时间：2021年4月28日 上午9:39:49
*/
@Service
public class ITransferServiceImpl implements ITransferService {

	private static Logger logger = LoggerFactory.getLogger(ITransferServiceImpl.class);

	@Reference
	private IAccountService accountService;

	@Autowired
	private RedissonClient redissonClient;

	@Autowired
	private AccountMapper accountMapper;

	@Override
	@GlobalTransactional(timeoutMills = 300000)
	public int transfer(Account account) throws Exception {
		RLock fairLock = null;
		int status =0;
		try {
			String key = Constants.getUserKey("1");
			logger.info("正在尝试获取分布式锁...");
			fairLock=redissonClient.getFairLock(key);
			fairLock.lock();
			logger.info("分布式锁获取 SUCCESS");
			logger.info("开始转账:{}",com.alibaba.fastjson.JSONObject.toJSONString(account));
			if(account == null || account.getTotalMoney() == null || account.getId() ==null || BigDecimal.ZERO.compareTo(account.getTotalMoney())==0){
				throw  new Exception("参数异常!");
			}
			Account dbAccount=accountMapper.selectByPrimaryKey(account.getId());
			if(dbAccount == null){
				throw new Exception("未查询到账户信息");
			}
			if(dbAccount.getTotalMoney()==null){
				throw new Exception("账户金额异常");
			}
			if(account.getTotalMoney().compareTo(dbAccount.getTotalMoney())>0 ){
				throw new Exception("余额不足");
			}

			//更新李永健余额
			Account updateAccount = new Account();
			updateAccount.setTotalMoney(dbAccount.getTotalMoney().subtract(account.getTotalMoney()));
			updateAccount.setVersion(dbAccount.getVersion()+1);

			AccountExample example = new AccountExample();
			example.createCriteria().andIdEqualTo(account.getId()).
					andVersionEqualTo(dbAccount.getVersion()).andDeletedEqualTo(Constants.DELETE_0);
			//更新金额
			int tranfrerStatus= accountMapper.updateByExampleSelective(updateAccount,example);
			if(tranfrerStatus >0){
				//将钱转给娄伟
				account.setId(2L);
				status = accountService.transfer(account);
				if(status >0){
					logger.info("转账成功,交易金额:{}",account.getTotalMoney());
				}
			}else{
				throw new Exception("已经存在交易,请稍后重试");
			}
			if(account.getTotalMoney().compareTo(new BigDecimal("100"))>0){
				throw new Exception("交易金额过多");
			}

		}catch (Exception e){
			throw  e;
		}finally {
			if(fairLock !=null ){
				fairLock.unlock();
				logger.info("分布式锁释放成功");
			}
		}
		return status;
	}
}
